// @ts-nocheck

import axios from 'axios'
import { getToken, downloadBlob, removeToken } from './index'
import CONSTANTS from "@/utils/constants";
import { ElMessage as Message, ElMessageBox as MessageBox } from 'element-plus'
import { showLoading, hideLoading } from './loading'

const qs = require('qs')

const instance = axios.create({
    timeout: 60 * 1000, //请求超时时间
    baseURL: 'http://10.0.31.199:1991',
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
})


// 请求头拦截器
instance.interceptors.request.use(
    config => {
        showLoading()
        if (getToken()) {
            config.headers['Authorization'] = 'Bearer ' + getToken()
        } else {
            config.headers['Authorization'] = 'Basic c2NvOmRtcw=='
        }

        return config
    },
    error => {
        return Promise.reject(error);
    }
)

//添加response拦截器
instance.interceptors.response.use(
    response => {
        hideLoading()

        // 文件流转文件导出
        if (response.data instanceof Blob) {
            let excelName = qs.parse(response.request.responseURL.split('?')[1]).excelName
            if (response.config.method == 'post') {
                excelName = JSON.parse(response.config.data).excelName
            }
            let query = {}
            if (response.config.method === 'post') {
                query = qs.parse(response.config.data)
            } else {
                query = qs.parse(response.request.responseURL.split('?')[1])
            }
            downloadBlob(
                response.data,
                excelName,
                query.suffix || 'xls'
            )
            return response
        }

        const config = response.config
        const res = response.data
        if (config && config.url.indexOf("auth/oauth/token") > -1) {
            return response
        }
        if (res.code != 200) {
            if (res.code === 401) {
                MessageBox.confirm('您的登录已过期，请重新登录！', '重新登录', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    removeToken()
                })
            } else {
                Message({
                    message: res.message || res.msg || res.text || 'Error',
                    type: 'error',
                    duration: 5 * 1000
                })
            }
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res
        }
    },
    error => {
        hideLoading()
        if (error.message.includes('Network Error')) {
            Message.error("网络错误，请检查网络连接！")
        } else if (error.message.indexOf('Maximum') !== -1) {
            Message.error("mockjs内存溢出")
        } else {
            Message.error(error.message || "用户鉴权失败！")
        }
        return Promise.reject(error)
    }
)



//封装get方法
export function get(url, data = {}, content_type, response_type = 'json') {
    let contentType = content_type || CONSTANTS.CONTENT_TYPE_JSON
    if (typeof data.useMock !== 'undefined' && data.useMock === false) {
        delete data.useMock
    }
    return new Promise((resolve, reject) => {
        instance.get(url, {
            params: data,
            headers: { 'Content-Type': contentType },
            responseType: response_type
        }).then(response => {
            resolve(response.data)
        }).catch(err => {
            reject(err)
        })
    })
}

//封装post方法
export function post(url, data = {}, content_type, response_type = 'json') {
    let contentType = content_type || CONSTANTS.CONTENT_TYPE_JSON
    if (typeof data.useMock !== 'undefined' && data.useMock === false) {
        delete data.useMock
    }
    let params = {}
    if (contentType.indexOf('json') !== -1) {
        params = JSON.stringify(data)
    } else if (contentType.indexOf('multipart') !== -1) {
        params = data
    } else {
        params = qs.stringify(data)
    }
    return new Promise((resolve, reject) => {
        instance.post(url, params, { headers: { 'Content-Type': contentType }, responseType: response_type }).then(response => {
            resolve(response.data)
        }, err => {
            reject(err)
        })
    })
}

// 封装put方法
export function put(url, data = {}, content_type, response_type = 'json') {
    let contentType = content_type || CONSTANTS.CONTENT_TYPE_JSON
    if (typeof data.useMock !== 'undefined' && data.useMock === false) {
        delete data.useMock
    }
    let params = {}
    if (contentType.indexOf('json') !== -1) {
        params = JSON.stringify(data)
    } else if (contentType.indexOf('multipart') !== -1) {
        params = data
    } else {
        params = qs.stringify(data)
    }
    return new Promise((resolve, reject) => {
        instance.put(url, params, { headers: { 'Content-Type': contentType }, responseType: response_type }).then(response => {
            resolve(response.data)
        }, err => {
            reject(err)
        })
    })
}

// 封装delete方法
export function del(url, data = {}, content_type, response_type = 'json') {
    let contentType = content_type || CONSTANTS.CONTENT_TYPE_JSON
    if (typeof data.useMock !== 'undefined' && data.useMock === false) {
        delete data.useMock
    }
    return new Promise((resolve, reject) => {
        instance.delete(url, data, { headers: { 'Content-Type': contentType }, responseType: response_type }).then(response => {
            resolve(response.data)
        }, err => {
            reject(err)
        })
    })
}